package com.knife.redis;

import com.knife.redis.config.KnifeDynamicRedisTemplateFactory;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * 动态 RedisTemplate ，以支持动态切换 redis database
 *
 * @author bojiangzhou 2018/08/28
 */
public class KnifeDynamicRedisTemplate<K, V> extends KnifeAbstractRoutingRedisTemplate<K, V> {

    private final KnifeDynamicRedisTemplateFactory<K, V> dynamicRedisTemplateFactory;

    public KnifeDynamicRedisTemplate(KnifeDynamicRedisTemplateFactory<K, V> dynamicRedisTemplateFactory) {
        this.dynamicRedisTemplateFactory = dynamicRedisTemplateFactory;
    }

    @Override
    protected Integer determineCurrentLookupKey() {
        return KnifeRedisDatabaseThreadLocal.get();
    }

    @Override
    protected RedisTemplate<K, V> createRedisTemplateOnMissing(Object lookupKey) {
        return dynamicRedisTemplateFactory.createRedisTemplate((Integer) lookupKey);
    }

}
